<template>
	<!--#ifndef MP-WEIXIN-->
	<text v-if="visible" class="cuIcon-voice text-lg" @click="startRecognize"></text>
	<!--#endif-->
	<!-- #ifdef MP-WEIXIN-->
	<view class="cu-load load-modal speech" v-if="loadModal" @click="stopRecognize"> 
		<!-- <view class="cuIcon-emojifill text-orange"></view> -->
		<text class="cuIcon-voice text-green" ></text>
		<view class="gray-text">{{ value }}</view>
	</view>
	<!--#endif-->
	<!-- <view>
		<view class="voicepad">  
		            {{voiceState}}  
		        </view>  
		        <button class="cu-btn  bg-green voicebtn " @touchstart="touchStart" @touchend="touchEnd"><text class="cuIcon-voicefill"></text></button>  
	</view> -->
</template>
<script>
// #ifdef APP-PLUS
import permision from '@/platforms/app-plus/permission.js';
// #endif
// #ifdef MP-WEIXIN
var plugin = requirePlugin('WechatSI');
let manager = plugin.getRecordRecognitionManager();
// #endif
import util from '@/common/util';
export default {
	data() {
		return {
			value: '',
			callback: null, //用于微信小程序
			loadModal: false,
			timeout: 5
		};
	},
	props: {
		visible: {
			type: Boolean,
			default: true
		}
	},
	mounted() {
		// #ifdef MP-WEIXIN
		this.initMpWxRecord();
		// #endif
	},
	methods: {
		async startRecognize(callback) {
			// #ifdef H5
			util.msg("网页端暂不支持语音识别");
			// #endif
			// #ifdef MP-WEIXIN			
			this.callback = callback;
			var that = this;
			this.value = '';
			manager.start({
				duration: that.timeout * 1000,
				lang: 'zh_CN'
			});
			this.loadModal = true;
			// #endif
			// #ifdef APP-PLUS
			let status = await this.checkPermission();
			if (status !== 1) {
				return;
			}
			// TODO ios 在没有请求过权限之前无法得知是否有相关权限，这种状态下需要直接调用语音，会弹出正在识别的toast
			var options = {};
			var that = this;
			//options.engine = 'baidu';
			that.value = '';
			plus.speech.startRecognize(
				options,
				function(s) {
					console.log(s);
					that.value += s;
					if (typeof callback == 'function') {
						callback(that.value);
					}
				},
				function(e) {
					console.log('语音识别失败：' + e.message);
					util.msg('语音识别失败：' + e.message);
				}
			);
			// #endif
		},
		async startRecognizeEnglish() {
			// #ifdef APP-PLUS
			let status = await this.checkPermission();
			if (status !== 1) {
				return;
			}

			// TODO ios 在没有请求过权限之前无法得知是否有相关权限，这种状态下需要直接调用语音，会弹出正在识别的toast
			var options = {};
			var that = this;
			options.engine = 'baidu';
			options.lang = 'en-us';
			that.value = '';
			plus.speech.startRecognize(
				options,
				function(s) {
					//console.log(s);
					that.value += s;
					if (typeof callback == 'function') {
						callback(that.value);
					}
				},
				function(e) {
					console.log('语音识别失败：' + e.message);
					util.msg('语音识别失败：' + e.message);
				}
			);
			// #endif
		},
		stopRecognize() {
			// #ifdef MP-WEIXIN
			manager.stop();
			this.loadModal = false;
			// #endif
		},
		/**
		 * 小程序初始化语音识别回调
		 * 绑定语音播放开始事件
		 */
		// #ifdef MP-WEIXIN
		initMpWxRecord: function() {
			var that = this;
			manager.onStart = function(res) {
				//this.voiceState = 'onStart:' + res.msg + '正在录音';
			};
			//有新的识别内容返回，则会调用此事件
			manager.onRecognize = res => {
				that.value = res.result;
			};
			// 识别结束事件
			manager.onStop = function(res) {
				//this.voiceState = 'onStop' + res.result;
				that.loadModal = false;
				that.callback && that.callback(res.result);
				//util.msg('语音识别结果：' +res.result);
			};
			// 识别错误事件
			manager.onError = function(res) {
				//this.voiceState = 'onError' + res.msg;
				that.loadModal = false;
				util.msg('语音识别失败：' + res.msg);
			};
		},
		touchStart: function() {
			// uni.vibrateLong({
			//  success:function(){
			//  }
			// });
			var that = this;
			manager.start({
				duration: that * timeout * 1000,
				lang: 'zh_CN'
			});
		},
		touchEnd: function() {
			uni.showToast();
			manager.stop();
		},
		// #endif
		// #ifdef APP-PLUS
		async checkPermission() {
			let status = permision.isIOS ? await permision.requestIOS('record') : await permision.requestAndroid('android.permission.RECORD_AUDIO');

			if (status === null || status === 1) {
				status = 1;
			} else if (status === 2) {
				uni.showModal({
					content: '系统麦克风已关闭',
					confirmText: '确定',
					showCancel: false,
					success: function(res) {}
				});
			} else {
				uni.showModal({
					content: '需要麦克风权限',
					confirmText: '设置',
					success: function(res) {
						if (res.confirm) {
							permision.gotoAppSetting();
						}
					}
				});
			}
			return status;
		}
		// #endif
	}
};
</script>

<style lang="scss">
.voicebtn {
	height: 130upx;
	display: block;
	width: 130upx;
	line-height: 130upx;
	border-radius: 65upx;
	font-size: 50upx;
	position: absolute;
	top: 1060upx;
	left: 310upx;
}
.speech.cu-load.load-modal [class*='cuIcon-'] {
	font-size: 80rpx; 
}
.speech.cu-load.load-modal::after {
	border-left: 6upx solid #DDDDDD;   
}

/* .voicepad {
	height: 250upx;
	width: 680upx;
	background: #fff;
	margin: 30upx auto;
	border-radius: 8upx;
	color: #cccccc;
	padding: 20upx;
	font-size: 35upx;
} */
</style>
